<template>
  <div class="main_box" style="padding-right:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.printerId ? "编辑打印机" : "新增打印机" }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="printerType" label="打印机类型">
            <el-select v-model="dataForm.printerType" placeholder="请选择打印机类型" clearable>
              <el-option v-for="item in printerTypeList" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="printerVersion" label="打印机版本">
            <el-select v-model="dataForm.printerVersion" placeholder="请选择打印机版本" clearable>
              <el-option label="wifi版" :value="1"> </el-option>
              <el-option label="4G版" :value="2"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物联网卡号">
            <el-input v-model="dataForm.iccid"></el-input>
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="dataForm.name" @keydown.native="keydown($event)"></el-input>
          </el-form-item>
          <el-form-item label="打印机编号" prop="sn">
            <el-input v-model="dataForm.sn"></el-input>
          </el-form-item>
          <el-form-item label="设备密钥" prop="printerKey">
            <el-input v-model="dataForm.printerKey"></el-input>
          </el-form-item>
          <el-form-item label="时间点" prop="timePoints">
            <el-select v-model="dataForm.timePoints" multiple clearable filterable placeholder="最多可以选择五个时间">
              <el-option v-for="item in timeList" :key="item.value" :value="item.value" :label="item.label"
                :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="特殊内容标识" prop="contentFlag">
            <el-radio-group v-model="dataForm.contentFlag">
              <el-radio label="0">无</el-radio>
              <el-radio label="1">呼叫器首单</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row v-show="dataForm.printerType === 1">
          <div class="tit">
            <h2>关联商户</h2>
            <el-button @click="addRelationBusiness" circle type="success" icon="el-icon-plus">
            </el-button>
          </div>
          <el-table :data="dataForm.list" style="width:fit-content;margin-top:10px">
            <el-table-column align="center" width="100" label="操作">
              <template slot-scope="scope">
                <el-button @click="subRelationBusiness(scope.$index)" plain type="danger" circle icon="el-icon-minus">
                </el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" width="300" label="商户">
              <template slot-scope="scope">
                <el-select v-model="scope.row.businessId" @change="businessChange(scope.row)" clearable filterable>
                  <el-option v-for="item in businessList" :label="item.name" :value="item.id" :key="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="300" label="部门">
              <template slot-scope="scope">
                <el-cascader style="width:250px" @focus="getDepartList(scope.row)" v-model="scope.row.departId"
                  :options="scope.row.departList" :props="{
                    label: 'departName',
                    value: 'departId',
                    checkStrictly: true
                  }" clearable filterable>
                </el-cascader>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import PrinterApi from "@/api/equip/printer";
import DepartApi from "@/api/business/depart";
import BusinessApi from "@/api/business/business";
export default {
  name: "PrinterAdd",
  data() {
    return {
      dataForm: {
        printerType: 1,
        printerId: "",
        iccid: "",
        name: "",
        sn: "",
        printerKey: "",
        remark: "",
        timePoints: [],
        printerVersion: "",
        list: [
          {
            businessId: "",
            departId: [],
            departList: []
          }
        ],
        contentFlag: ''
      },
      timeList: [],
      departList: [],
      printerTypeList: [{ id: 1, name: "商户" }, { id: 2, name: "平台" }],
      businessList: [],
      roleRules: {
        printerType: [
          { required: true, message: "请选择打印机类型", trigger: "change" }
        ],
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        sn: [{ required: true, message: "请输入打印机编号", trigger: "blur" }],
        printerKey: [
          { required: true, message: "请输入设备密钥", trigger: "blur" }
        ],
        printerVersion: [
          { required: true, message: "请选择打印机版本", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    "dataForm.timePoints": {
      handler(val) {
        if (val.length == 5) {
          this.timeList.forEach(item => {
            if (!val.includes(item.value)) {
              this.$set(item, "disabled", true);
            } else {
              this.$delete(item, "disabled");
            }
          });
        } else {
          this.timeList.forEach(item => this.$delete(item, "disabled"));
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getBusinessList();
      this.getFiveIntTime();
      if (this.$route.query.id) {
        this.dataForm.printerId = this.$route.query.id;
        this.getData();
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      const cond = {
        id: this.dataForm.printerId
      };
      await this.getDepartList();
      const res2 = await PrinterApi.getPrinterInfo(cond);
      this.formatData(res2.data);
      this.$Utils.bindingBean(this.dataForm, res2.data);
    },
    /**
     *  获取全部是5整数的时间数组
     */

    getFiveIntTime() {
      let maxHours = 0;
      do {
        const val = maxHours > 9 ? "" + maxHours : "0" + maxHours;
        let maxMinutes = 0;
        do {
          const val2 = maxMinutes > 9 ? "" + maxMinutes : "0" + maxMinutes;
          const val3 = val + ":" + val2;
          this.timeList.push({ value: val3, label: val3 });
          maxMinutes = maxMinutes + 5;
        } while (maxMinutes < 60);
        maxHours++;
      } while (maxHours < 24);
    },
    formatData(data) {
      data.list.forEach(item => {
        if (item.departId) {
          let val = this.$Utils.filterTreeToArr(
            this.departList,
            item,
            "departId"
          );
          val = JSON.parse(JSON.stringify(val));
          item.departId = [];
          item.departList = [];
          val.forEach((item2, index) => {
            item.departId.push(item2.departId);
            if (index == 0) {
              item.departList = [item2];
            } else {
              let children = val[index - 1].children;
              children ? children.push(item2) : (children = [item2]);
            }
          });
        }
      });
      data.timePoints = data.timePoints ? data.timePoints.split(",") : [];
    },
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data;
      });
    },
    addRelationBusiness() {
      this.dataForm.list.push({
        businessId: "",
        departId: "",
        departList: []
      });
    },
    subRelationBusiness(index) {
      this.dataForm.list.splice(index, 1);
    },
    businessChange(row) {
      row.departId = [];
      row.departList = [];
      this.getBusinessList();
    },
    async getDepartList(row) {
      const params = {};
      if (row && !row.businessId) {
        return;
      } else if (row && row.businessId) {
        params.businessId = row.businessId;
      }
      const res = await DepartApi.listMangerTree(params);
      if (row) {
        if (row.hasOwnProperty("departList")) {
          row.departList = res.data;
        } else {
          this.$set(row, "departList", res.data);
        }
      } else {
        this.departList = res.data;
      }
    },
    checkData() {
      let { printerType, list } = this.dataForm;
      if (printerType == 1) {
        this.dataForm.list = list = list.filter(item => item.businessId);
        if (!list.length) {
          this.$message.error("请至少添加一个关联商户");
          return;
        }

        this.list = list.map(item => {
          const obj = Object.assign(
            {},
            { ...item },
            {
              departLevel: (item.departId && item.departId.length) || "",
              departId: (item.departId && item.departId.at(-1)) || ""
            }
          );
          delete obj.departList;
          return obj;
        });
      }
      return true;
    },
    sureClick() {
      // 提交
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (!this.checkData()) return;
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.dataForm.printerId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },
    editData() {
      // 编辑
      var cond = {
        printerId: this.dataForm.printerId,
        printerType: this.dataForm.printerType,
        name: this.dataForm.name,
        sn: this.dataForm.sn,
        timePoints: this.dataForm.timePoints.length
          ? this.dataForm.timePoints.join(",")
          : "",
        printerKey: this.dataForm.printerKey,
        list: this.dataForm.printerType === 1 ? this.list : [],
        remark: this.dataForm.remark,
        printerVersion: this.dataForm.printerVersion,
        iccid: this.dataForm.iccid,
        contentFlag: this.dataForm.contentFlag
      };
      PrinterApi.editPrinter(cond).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    addData() {
      // 新增
      var cond = {
        printerType: this.dataForm.printerType,
        name: this.dataForm.name,
        sn: this.dataForm.sn,
        timePoints: this.dataForm.timePoints.length
          ? this.dataForm.timePoints.join(",")
          : "",
        printerKey: this.dataForm.printerKey,
        list: this.dataForm.printerType === 1 ? this.list : [],
        remark: this.dataForm.remark,
        printerVersion: this.dataForm.printerVersion,
        iccid: this.dataForm.iccid,
        contentFlag: this.dataForm.contentFlag
      };
      PrinterApi.addPrinter(cond).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({ path: "/equip/printerManagement" });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss"></style>
